from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types
from django.contrib.auth.hashers import make_password, check_password

# Create your views here.


#商品分类添加页面
def typesadd(request):

    context = {'tlist':GetTypesAll()}
    return render(request,'admin/types/add.html',context)

# 执行商品添加
def typesinsert(request):
    try:
        #创建模型对象
        ob = Types()
        ob.name = request.POST['name']
        ob.pid = request.POST['pid']
        if ob.pid == '0':
            ob.path = '0,'
        else:
            #如果不是添加的顶级分类,需要获取父类的path路径,拼接pid
            p = Types.objects.get(id=ob.pid)
            ob.path = p.path + str(ob.pid)+','
        ob.save()

        return HttpResponse('<script>alert("添加成功");location.href="/admin/types/list/"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/admin/types/add/"</script>')

#商品分类列表页
def typeslist(request):

    #搜索参数
    keywords = request.GET.get('keywords','') 
    data = GetTypesAll(keywords)
    

    #数据分页类
    from django.core.paginator import Paginator

    #实例化分类页 参数1查询的数据 参数2 每页显示的数据
    paginator = Paginator(data,10)


    #当前页码
    p= int(request.GET.get('p',1))

    #根据当前页码获取当前页显示的数据
    typeslist=paginator.page(p)

    # #获取当前页的页码数
    # num = paginator.page_range

    #获取数据
    context = {'tlist':typeslist}
    return render(request,'admin/types/list.html',context)




#编辑
def typesedit(request,tid):
    #根据tid获取当前数据对象
    ob = Types.objects.get(id=tid)

    context = {'tinfo':ob,'tlist':GetTypesAll()}
    return render(request,'admin/types/edit.html',context)

#执行修改
def typesupdate(request):
    try:
        #获取当前对象,执行修改
        ob = Types.objects.get(id=request.POST['tid'])
        ob.name=request.POST['name']
        ob.save()

        return HttpResponse('<script>alert("修改成功");location.href="/admin/types/list/"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/admin/types/edit/'+request.POST['tid']+'/"</script>')




#删除
def typesdel(request):
    #查询当前类下是否有子类
    num = Types.objects.filter(pid=request.GET['tid']).count()

     # 判断是否还子类
    if num :
        # 还有子类
        return JsonResponse({'status':1,'msg':'已分类,删除失败'})

    # 没有子类
    ob = Types.objects.get(id = request.GET['tid'])
    ob.delete()

    return JsonResponse({'status':0,'msg':'未分类,删除成功'})





#获取所有分类排序的封装函数
def GetTypesAll(keywords=''):
    if keywords:
        ob = Types.objects.filter(name__contains=keywords)
    else:
        ob = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')


    for x in ob:
        # 控制当前对象的缩进
        n=len(x.path.split(','))-2
        # n = int(len(x.path)/2)-1
        x.name = (n*'->')+x.name

        #给当前对象添加一个所属父类的属性
        if x.pid == 0:
            x.pname = '顶级分类'
        else:
            obj = Types.objects.get(id=x.pid)
            x.pname = obj.name
    return ob